//判断字符串是否能转化为json
function isJsonFormat( str ) {
  try {
      $.parseJSON(str);
  } catch (e) {
      return false;
  }
  return true;
}
$(document).ready(function () {
  $('.submit').click(function () {
    var pathname = window.location.pathname;
    var route = pathname.substring(6);
    var jsonData=$('#data').val();
    var inputRoute=$('#route').val();
    console.log(route)
    if(isJsonFormat(jsonData)&&inputRoute){
          if (route === '') {
      $.post('/ajax/postData', {
        portName: $('#port').val(),
        route: $('#route').val(),
        jsonData: $('#data').val().replace(/[\r\n]/g,""),
        listNum: $('#route').val()
      }).then(function (res) {
        // console.log(res);
        if (res.code == 200) {
          if (res.data.message === 'false') {
            alert('路由已经被占用')
          }
          else {
              window.location.href='/list';
          }
        }
      })
    }
    else {
      console.log(route)
      $.post('/ajax/modifyData', {
        portName: $('#port').val(),
        route: $('#route').val(),
        jsonData: $('#data').val().replace(/[\r\n]/g,""),
        listNum: route
      }).then(function (res) {
        // console.log(res)
        if(route!==$('#route').val()){
          if (res.data.message === 'false') {
            alert('路由已经被占用')
          }
          else{
            if (res.code == 200) {
              window.location.href='/list';
          }
          }
        }
        else {
          // console.log(res);
          if (res.code == 200) {
              window.location.href='/list';
          }
        }
      })
    }
    }
    else{
      alert('数据不是json格式，请修改后再进行提交')
    }


  })

})

$.get('/page/'+localMid).then(function (list) {
  console.log( $.parseJSON(JSON.stringify(data)));
  if (localMid !== '') {
    
    $('#port').val(portName);
    $('#route').val(route);
      $('#data').val(jsonData.replace(/[\r\n]/g,"").replace(/&quot;/g,'"').replace(/&#39;/g,'\''));
  }
})
$('.doEmpty').on('click', function () {
  $('#port').val('');
  $('#route').val('');
  $('#data').val('');
})

